﻿var GroupList = function () {
    var postData = {};

    toastr.options = {
        "closeButton": false,
        "debug": false,
        "positionClass": "toast-top-center",
        "onclick": null,
        "showDuration": "500",
        "hideDuration": "500",
        "timeOut": "2000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };

    // 初始化列表
    var initTable = function () {
        var container = $("#table_content");

        var lb = new LoadingBox("#table_content");
        lb.Text = "数据载入中...";

        container
        .delegate("ul.pagination li:not(.disabled, .active) > a", "click", function () {
            xhrRequest(this.href);
            return false;
        })
        .delegate("ul.pagination li.disabled > a, ul.pagination li.active > a", "click", function () {
            return false;
        })
        .delegate("#tableview .group-checkable", "change", function () {
            var set = jQuery(this).attr("data-set");
            var checked = jQuery(this).is(":checked");
            jQuery(set).each(function () {
                if (checked) {
                    $(this).attr("checked", true);
                } else {
                    $(this).attr("checked", false);
                }
            });
            jQuery.uniform.update(set);
        });

        function xhrRequest(post_url) {
            lb.Show();
            postData["ajax"] = true;

            $.ajax({
                url: post_url,
                data: postData,
                type: "POST",
                success: function (html, txtStatusCode) {
                    if (html.Result == null) {
                        container.empty().append(html);
                    } else {
                        if (!html.Result) toastr["error"]("遇到不可预知的错误，查询被中断", "查询数据");
                    }
                },
                complete: function () {
                    Metronic.initComponents();
                    lb.Hide();
                }
            });
        }

        // 刷新表
        GroupList.Refresh = function () {
            xhrRequest(location.href);
        }
    };

    // 初始化删除组表单
    var initDeleteGroupForm = function () {
        var confirmpwd = $("#txtConfirmpwd");

        $("#deleteGroupForm")
        .AjaxForm({
            submitButton: {
                selector: "#btnDeleteConfirm",
                loadingText: "正在删除"
            },
            resetButton: {
                selector: "#btnDeleteCancel"
            },
            alertTitle: "删除分组",
            data: function () {
                var params = [];
                params.push({ "name": "confirmpwd", "value": confirmpwd.val() });
                $("#tableview")
                    .children("tbody")
                    .find("input[type='checkbox'][name='gids']:checked")
                    .each(function () {
                        params.push({ "name": "gids", "value": this.value });
                    });

                return params;
            },
            validate: function (data, title) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i]["name"] == "gids") return true;
                }

                var msg = "没有选择需要删除的分组";
                if (title) {
                    toastr["warning"](msg, title);
                } else {
                    toastr["warning"](msg);
                }

                return false;
            },
            success: function (response, title) {
                var args = [];
                args.push(response.Message);
                if (title) args.push(title);

                if (response.Result) {
                    toastr["success"].apply(this, args);
                    GroupList.Refresh();
                } else {
                    toastr["error"].apply(this, args);
                }
            }
        })
        .validate({
            onsubmit: false,
            rules: {
                confirmpwd: "required"
            },
            messages: {
                confirmpwd: "确认密码必填"
            },
            errorPlacement: function (error, element) {
                element.parent().removeClass("has-success").addClass("has-error");
            },
            success: function (label, element) {
                $(element).parent().removeClass("has-error").addClass("has-success");
            }
        });
    };

    // 初始化创建分组表单
    var initAddGroupForm = function () {
        // 附加验证方法
        jQuery.validator.addMethod(
            "gidRule",
            function (value, element) {
                return this.optional(element) || /(^_.*$)|[^_\w\d]/.test(value)
            },
            "GID不合法，必须以下划线开头且只能以字符数字及下划线组成。"
        );

        $("#addGroupForm")
        .AjaxForm({
            submitButton: {
                selector: "#btnCreate",
                loadingText: "正在创建"
            },
            resetButton: {
                selector: "#btnCancel"
            },
            alertTitle: "创建分组",
            success: function (response, title) {
                var args = [];
                args.push(response.Message);
                if (title) args.push(title);

                if (response.Result) {
                    toastr["success"].apply(this, args);
                    GroupList.Refresh();
                } else {
                    toastr["error"].apply(this, args);
                }
            }
        })
        .validate({
            onsubmit: false,
            rules: {
                gid: {
                    required: true,
                    minlength: 3,
                    maxlength: 15,
                    gidRule: true
                },
                groupname: {
                    required: true,
                    maxlength: 10
                },
                descr: {
                    maxlength: 30
                }
            },
            messages: {
                gid: {
                    required: "组ID必填",
                    minlength: "过短",
                    maxlength: "过长"
                },
                groupname: {
                    required: "组名必填",
                    maxlength: "组名过长"
                },
                descr: {
                    maxlength: "描述过长"
                }
            },
            errorPlacement: function (error, element) {
                element.closest(".form-group").removeClass("has-success").addClass("has-error");
            },
            success: function (label, element) {
                $(element).closest(".form-group").removeClass("has-error").addClass("has-success");
            }
        });
    };

    // 初始化添加到组
    var initAppendToGroup = function () {
        var userList = $("#user-list");

        userList
            .children("li")
            .bind("click", function () {
                $(this).find("input[type='checkbox']").trigger("click");
            });

        $("#appendToGroupForm").AjaxForm({
            submitButton: {
                selector: "#btnAppendToGroup",
                loadingText: "正在执行"
            },
            resetButton: {
                selector: "#btnAppendToGroupCancel",
                reset: function () {
                    this.find("input[type='checkbox']:checked")
                        .each(function () {
                            $(this).trigger("click");
                        });
                }
            },
            alertTitle: "添加成员",
            success: function (response, title) {
                var args = [];
                args.push(response.Message);
                if (title) args.push(title);

                if (response.Result) {
                    toastr["success"].apply(this, args);
                    GroupList.Refresh();
                } else {
                    toastr["error"].apply(this, args);
                }
            },
            data: function () {
                var params = this.serializeArray();
                $("#tableview")
                    .children("tbody")
                    .find("input[type='checkbox'][name='gids']:checked")
                    .each(function () {
                        params.push({ "name": "gids", "value": this.value });
                    });

                return params;
            },
            validate: function (data, title) {
                var validatedGID = false;
                var validatedUID = false;
                for (var i = 0; i < data.length; i++) {
                    if (data[i]["name"] == "gids") {
                        validatedGID = true;
                    }
                    if (data[i]["name"] == "uids") {
                        validatedUID = true;
                    }

                    if (validatedUID && validatedGID) return true;
                }

                var msg = "";
                if (!validatedUID && !validatedGID) {
                    msg = "没有选择需要添加的成员以及被添加的组";
                } else if (!validatedUID) {
                    msg = "没有选择需要添加的成员";
                } else {
                    msg = "没有选择需要被添加的组";
                }

                if (title) {
                    toastr["warning"](msg, title);
                } else {
                    toastr["warning"](msg);
                }

                return false;
            }
        });
    };

    // 初始化组详细信息面板
    var initGroupDetailPanel = function () {
        var panel = $("#group_detail_panel");

        panel.Body = $("#group_detail_panel_body");

        panel.on("show.bs.modal", function (e) {
            panel.Body.empty().append(
                '<img src="/assets/global/img/loading-spinner-grey.gif" alt="" class="loading">' +
				'<span>&nbsp;&nbsp;Loading... </span>');
        });
    };

    return {
        init: function () {
            initTable();
            initDeleteGroupForm();
            initAddGroupForm();
            initAppendToGroup();
            initGroupDetailPanel();
        },
        initTable: function () {
            initTable();
        },
        initDeleteGroupForm: function () {
            initDeleteGroupForm();
        },
        initAddGroupForm: function () {
            initAddGroupForm();
        },
        initAppendToGroup: function () {
            initAppendToGroup();
        },
        initGroupDetailPanel: function () {
            initGroupDetailPanel();
        }
    };
} ();